<?php

namespace App\Model;

use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\Db\Cursor;
use EasySwoole\ORM\Db\CursorInterface;
use EasySwoole\ORM\Exception\Exception;
use Throwable;

/**
 * Class UserPartakeModel
 * Create With Automatic Generator
 * @property $id
 * @property $user_id
 * @property $partake_num
 * @property $ongoing_num
 * @property $finish_num
 * @property $finish_percent
 * @property $prize
 * @property $create_time
 * @property $update_time
 */
class UserPartakeModel extends AbstractModel
{
    protected $tableName = 'bee_user_partake';

    protected $primaryKey = 'id';

    protected $autoTimeStamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * 添加到排行榜
     * @param int $userId
     * @param int $status
     * @param float $finishPercent
     * @param float $tmpPrize
     * @return UserPartakeModel|array|bool|AbstractModel|Cursor|CursorInterface|null
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws Exception
     * @throws Throwable
     */
    public function addUserPartake(int $userId, int $status, float $finishPercent, float $tmpPrize)
    {
        $res = $this->data([
            'user_id' => $userId,
            'partake_num' => 1,
            'finish_num' => $status ? 1 : 0,
            'finish_percent' => $finishPercent,
            'prize' => $tmpPrize,
            'update_time' => time(),
        ], false)->save();
        return $this->get($res);
    }

    /**
     * 更新用户排行榜信息
     * @param int $id
     * @param array $data
     * @return UserPartakeModel|array|bool|AbstractModel|Cursor|CursorInterface|null
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function updateUserPartake(int $id, array $data)
    {
        if (!count($data)) {
            return false;
        }

        $info = $this->get($id);
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $this->$k = QueryBuilder::$v[0]($v[1]);
            } else {
                $this->$k = $v;
            }
        }
        $info->update();

        return $info;
    }
}